package com.lz.ovuola.util.redis.cluster;

import java.io.Serializable;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.JedisCluster;

@Component
public class JedisClusterRepository {
	@Resource
	private HessianSerializer hessianSerializer;

	@Autowired
	private JedisCluster jedisCluster;

	public void set(String nameSpace, String key, String value) {
		jedisCluster.set(generateKey(nameSpace, key), value);
	};

	public void setEx(String nameSpace, String key, String value, int seconds) {
		jedisCluster.setex(generateKey(nameSpace, key), seconds, value);
	};

	public String get(String nameSpace, String key) {
		return jedisCluster.get(generateKey(nameSpace, key));
	};

	public void hset(String nameSpace, String key, String field,
			Serializable value) {
		jedisCluster.hset(generateKey(nameSpace, key).getBytes(),
				field.getBytes(), hessianSerializer.serialize(value));
	};

	public Serializable hget(String nameSpace, String key, String field) {
		return hessianSerializer.deserialize(jedisCluster.hget(
				generateKey(nameSpace, key).getBytes(), field.getBytes()));
	};

	/**
	 * 生成key
	 * 
	 * @param nameSpace
	 * @param key
	 * @return
	 */
	private String generateKey(String nameSpace, String key) {
		return new StringBuilder().append(nameSpace).append("_").append(key)
				.toString();
	}

}
